package com.nlp.trie.experiment1;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 词库
 * @author ygsong.abcft
 *
 */
public class Thesaurus {

	/**
	 * 存储结构
	 * Entry<单词, 次数>
	 */
	private List<Entry<String, Integer>> list = new ArrayList<>();
	
	/**
	 * 加载词库，初始化
	 * @param content
	 */
	public Thesaurus(String content) {
		//进行分词统计
		final Map<String, Integer> MAP = createMAP(content);
		//排序并存入list中
		sortMapByValue(MAP);
	}
	
	/**
	 * 分词
	 * @param str 分词的句子
	 * @param symbol 分割符号
	 * @return
	 */
	public String spitWord(final String str, final String symbol) {
		StringBuilder target = new StringBuilder();
		int start = 0;
		while (start < str.length()) {
			boolean noWord = true;
			for (int end = str.length(); end > start; end--) {
				String now = str.substring(start, end);
				for (Entry<String, Integer> e : list) {
					if (e.getKey().equals(now)) {
						target.append(symbol).append(now);
						start = end;
						noWord = false;
						break;
					}
				}
			}
			if (noWord) {
				target.append(symbol).append(str.charAt(start++));
			}
		}
		return target.substring(symbol.length()).toString();
	}
	
	/**
	 * 分词
	 * @param str 要分的句子
	 * @return 分词后的字符串数组
	 */
	public String[] spitWord(final String str) {
		return spitWord(str, ",,,,").split(",,,,");
	}

	/**
	 * 对map按照value排序，并存入list中
	 * @param map
	 */
	private void sortMapByValue(Map<String, Integer> map) {
		//这里将map.entrySet()转换成list
		list.addAll(map.entrySet());
		//然后通过比较器来实现排序
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {

			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		
	}

	/**
	 * 对文本alls的内容进行分词统计，存入map中
	 * @param alls
	 * @return
	 */
	private Map<String, Integer> createMAP(String alls) {
		System.out.println(alls);
		final Map<String, Integer> map = new HashMap<String, Integer>();
		//去掉空白符号
		StringBuilder sb = new StringBuilder(alls.replaceAll("\\s", ""));
		int start = 0;
		while(start < sb.length()) {
			int end = sb.indexOf("/", start+1);
			if (sb.charAt(end+1) != 'm') {
				String s = sb.substring(start, end);
				if (map.containsKey(s)) {
					map.put(s, map.get(s)+1);
				}else {
					map.put(s, 1);
				}
			}
			start = end+2;
		}
		return map;
	}
	
	public List<Entry<String, Integer>> getList() {
		return list;
	}
}
